package com.fafa.thread;

public class syn {
    public static void main(String[] args) {
        new Thread(new sellTicket(), "第一号祥").start();
        new Thread(new sellTicket(), "第二号祥").start();
        new Thread(new sellTicket(), "第三号祥").start();


    }
}

class  sellTicket implements Runnable {
    private static int ticket = 100;
    private boolean next = true;
    private static final Object object = new Object();

    private /*synchronized*/ boolean sell() //同步方法 方法锁
    {
        synchronized (/*this*/ object) //同步代码块
        {
            //代码块锁必须保证是同一个对象
            //实现了Runnable接口,
            //总是实现了class com.fafa.thread.sellTicket这个对象
            if (ticket <= 0) {
                System.out.println("收票结束");
                return false;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(Thread.currentThread().getName() + "余剩票数=" + ticket--);
            return true;
        }


    }

    @Override
    public void run() {

        while (next) {
            next = sell();
        }

    }
}